package com.fancy.learncenter.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.activity.H5Activity;
import com.fancy.learncenter.activity.MsgCommentActivity;
import com.fancy.learncenter.activity.MsgXTActivity;
import com.fancy.learncenter.activity.ReplyCommentActivity;
import com.fancy.learncenter.bean.BannerListDataBean;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.MsgSysDataBean;
import com.fancy.learncenter.bean.UnReadMsg;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.superservice.lya.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.model.Conversation;

/**
 * A simple {@link Fragment} subclass.
 */
public class MsgFragment extends Fragment {


    @Bind(R.id.list_view)
    ListView listView;
    List<Msg> list = new ArrayList<>();
    @Bind(R.id.ad_simdraweeview)
    SimpleDraweeView adSimdraweeview;
    @Bind(R.id.close_gg)
    ImageView closeGg;
    @Bind(R.id.ad_LL)
    FrameLayout adLL;

    public MsgFragment() {
        // Required empty public constructor
    }

    int unReadMsg = 0;
    int unReadCommemt = 0;
    int unReadReply = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_msg, container, false);
        ButterKnife.bind(this, view);
        intData();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
//                    case 0:
//                        startActivity(new Intent(getActivity(), ConversationListActivity.class).putExtra("title", "来自HR的消息"));
//                        break;
                    case 0:
                        startActivity(new Intent(getActivity(), ReplyCommentActivity.class));
                        break;
                    case 1:
                        startActivity(new Intent(getActivity(), MsgCommentActivity.class));
                        break;
                    case 2:
                        startActivity(new Intent(getActivity(), MsgXTActivity.class));
                        break;

                }
            }
        });

        bannerList();

        intConversationList();

        return view;
    }


    private void intConversationList() {
        ConversationListFragment fragment = new ConversationListFragment();
        Uri uri = Uri.parse("rong://" + MyApplication.getInstance().getContext().getPackageName()).buildUpon()
                .appendPath("conversationlist")
                .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false")
                .build();
        fragment.setUri(uri);
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.msg_frg, fragment);
        transaction.commit();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
            getReplyDatas();
        }
    }

    BaseAdapter itemAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.layout_msg, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.icon.setImageResource(list.get(i).icon);
            holder.title.setText(list.get(i).title);
            holder.content.setText(list.get(i).content);
            holder.data.setText(list.get(i).data);


            if (list.get(i).getUnRead() > 0) {

                holder.read_num.setVisibility(View.VISIBLE);
                if (list.get(i).getUnRead() >= 99) {
                    holder.read_num.setText("99+");
                } else {
                    holder.read_num.setText(list.get(i).getUnRead() + "");
                }
            } else {

                holder.read_num.setVisibility(View.GONE);


            }


            return convertView;
        }
    };

    private void intData() {
//        list.add(new Msg(R.mipmap.ic_hr, "我的聊天信息", "", ""));
        list.add(new Msg(R.mipmap.ic_huifu, "回复“我的”消息", "", ""));
        list.add(new Msg(R.mipmap.ic_liuyan, "给我留言的消息", "", ""));
        list.add(new Msg(R.mipmap.ic_xitong, "系统消息", "", ""));

//        Msg msg = list.get(0);
//        msg.setUnRead(Integer.parseInt(((MainActivity) getActivity()).unreadNum.getText().toString()));
//
//        msg.setContent("未读消息" + Integer.parseInt(((MainActivity) getActivity()).unreadNum.getText().toString()) + "条");


        listView.setAdapter(itemAdapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.close_gg, R.id.ad_LL, R.id.service_ll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.close_gg:

                adLL.setVisibility(View.GONE);

                break;
            case R.id.ad_LL:

                break;
            case R.id.service_ll:

                RongIM.getInstance().startPrivateChat(getActivity(), "2687", "客服");
                break;
        }
    }

    class ViewHolder {
        @Bind(R.id.icon)
        ImageView icon;
        @Bind(R.id.title)
        TextView title;
        @Bind(R.id.content)
        TextView content;
        @Bind(R.id.data)
        TextView data;
        @Bind(R.id.read_num)
        TextView read_num;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    class Msg {
        public int icon;
        public String title;
        public String content;
        public String data;
        public int unRead;

        public Msg(int icon, String title, String content, String data) {
            this.icon = icon;
            this.title = title;
            this.content = content;
            this.data = data;
        }

        public int getIcon() {
            return icon;
        }

        public void setIcon(int icon) {
            this.icon = icon;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }

        public int getUnRead() {
            return unRead;
        }

        public void setUnRead(int unRead) {
            this.unRead = unRead;
        }
    }


    private void bannerList() {
        Map map = new HashMap();
        map.put("site", "11");

        HttpMehtod.getInstance().bannerList(map, new IdeaObserver<BaseDataBean<ArrayList<BannerListDataBean>>>() {

            @Override
            public void onSuccess(final BaseDataBean<ArrayList<BannerListDataBean>> arrayListBaseDataBean) {

                if (arrayListBaseDataBean.getData() != null && arrayListBaseDataBean.getData().size() > 0) {
                    adSimdraweeview.setImageURI(arrayListBaseDataBean.getData().get(0).getImgsrc());
                    adSimdraweeview.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            if (!TextUtils.isEmpty(arrayListBaseDataBean.getData().get(0).getLink())) {
                                Intent intent = new Intent(getActivity(), H5Activity.class);
                                intent.putExtra(H5Activity.URL_KEY, arrayListBaseDataBean.getData().get(0).getLink());
                                startActivity(intent);
                            }

                        }
                    });
                } else {
                    adSimdraweeview.setVisibility(View.GONE);
                    closeGg.setVisibility(View.GONE);
                    adLL.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }


    private void getReplyDatas() {
        getCommentDatas();
        getSysData();
        Map map = new HashMap();
        map.put("outType", "1");
        HttpMehtod.getInstance().unReadCommentReply(map, new IdeaObserver<BaseDataBean<UnReadMsg>>() {
            @Override
            public void onSuccess(BaseDataBean<UnReadMsg> listBaseDataBean) {
                Msg msg = list.get(0);
                msg.setUnRead(listBaseDataBean.getData().getTotal());


                if (listBaseDataBean.getData().getLastMessage() != null) {
                    msg.setContent(listBaseDataBean.getData().getLastMessage().getContent());
                }
                itemAdapter.notifyDataSetChanged();

            }

            @Override
            public void onFail(int errorCode) {
            }
        });
    }

    private void getCommentDatas() {
        Map map = new HashMap();
        map.put("outType", "1");
        HttpMehtod.getInstance().unReadComment(map, new IdeaObserver<BaseDataBean<UnReadMsg>>() {
            @Override
            public void onSuccess(BaseDataBean<UnReadMsg> listBaseDataBean) {
                Msg msg = list.get(1);
                msg.setUnRead(listBaseDataBean.getData().getTotal());

                if (listBaseDataBean.getData().getLastMessage() != null) {
                    msg.setContent(listBaseDataBean.getData().getLastMessage().getContent());
                }
                itemAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(int errorCode) {
            }
        });
    }

    private void getSysData() {
        Map map = new HashMap();
        map.put("outType", "1");
        HttpMehtod.getInstance().msgSystem(map, new IdeaObserver<BaseDataBean<MsgSysDataBean>>() {
            @Override
            public void onSuccess(BaseDataBean<MsgSysDataBean> msgSysDataBeanBaseDataBean) {
                Msg msg = list.get(2);
                msg.setUnRead(msgSysDataBeanBaseDataBean.getData().getTotal());
                if (msgSysDataBeanBaseDataBean.getData().getLastMessage() != null) {
                    msg.setContent(msgSysDataBeanBaseDataBean.getData().getLastMessage().getContent());
                }
                itemAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(int errorCode) {
            }
        });
    }

    public void notifyRead(int i) {
        Msg msg = list.get(0);
        msg.setUnRead(i);

        if (i > 0) {
            msg.setContent("未读消息" + i + "条");
        } else {
            msg.setContent("");
        }
        itemAdapter.notifyDataSetChanged();
    }
}
